#include "board_timer.h"
#include "board_config.h"

TIM_HandleTypeDef trigger_tim_handler;
TIM_HandleTypeDef dacTim;

void trigger_timer_init(void)
{
    /* micro second */
    uint32_t uwPrescalerValue =
        (uint32_t)((SystemCoreClock /2) / 1000000) - 1;

    /* Set TIMx instance */
    trigger_tim_handler.Instance = TRIGGER_TIMER;

    trigger_tim_handler.Init.Period = 1000000 / TRIGGER_FREQ - 1;
    trigger_tim_handler.Init.Prescaler = uwPrescalerValue;
    trigger_tim_handler.Init.ClockDivision = 0;
    trigger_tim_handler.Init.CounterMode = TIM_COUNTERMODE_UP;

    HAL_TIM_Base_Init(&trigger_tim_handler);

    HAL_TIM_Base_Start_IT(&trigger_tim_handler);
}

void dac_trigger_timer_init(uint16_t hz)
{
    TIM_MasterConfigTypeDef sMasterConfig;

    dacTim.Instance = DAC_TRIG_TIMER;

    dacTim.Init.Period = 1000000 / hz - 1;
    dacTim.Init.Prescaler = (uint32_t)((SystemCoreClock / 2) / 1000000) - 1;
    dacTim.Init.ClockDivision = 0;
    dacTim.Init.CounterMode = TIM_COUNTERMODE_UP;
    HAL_TIM_Base_Init(&dacTim);

    sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
    sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
    HAL_TIMEx_MasterConfigSynchronization(&dacTim, &sMasterConfig);

    HAL_TIM_Base_Start(&dacTim); /* TODO: better not start here? */
}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
{
    if (htim == &trigger_tim_handler) {
        /*##-1- Enable peripherals and GPIO Clocks */
        /* TIMx Peripheral clock enable */
        TRIGGER_TIMER_CLK_ENABLE();

        /*##-2- Configure the NVIC for TIMx */
        /* Set Interrupt Group Priority */
        HAL_NVIC_SetPriority(TRIGGER_TIMER_IRQn, 2, 0);

        /* Enable the TIMx global Interrupt */
        HAL_NVIC_EnableIRQ(TRIGGER_TIMER_IRQn);
    }
    if (htim == &dacTim) {
        DAC_TRIG_TIMER_CLK_ENABLE();
    }
}

void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim)
{
	if (htim == &dacTim) {
		DAC_TRIG_TIMER_CLK_DISABLE();
	}
}

